import './index.scss'
import { Divider, Radio, Space, Table, Button, Switch, Col, Form, Input, Row, Select, theme, DatePicker, Pagination, Modal, message, Upload } from 'antd';
import { useEffect, useState } from 'react';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import { scree } from '../../../utils/sendRequst';
import { delcj } from '../../../utils/sendRequst';
import { getcx } from '../../../utils/sendRequst';
import { addsc } from '../../../utils/sendRequst';
import { editsc } from '../../../utils/sendRequst';
import dayjs from 'dayjs'
import { Link } from 'react-router-dom';
import { render } from 'react-dom';
// const { RangePicker } = DatePicker;
const { Option } = Select;

// 图片相关方法
const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
};
// const beforeUpload = (file) => {
//     const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
//     if (!isJpgOrPng) {
//         message.error('You can only upload JPG/PNG file!');
//     }
//     const isLt2M = file.size / 1024 / 1024 < 2;
//     if (!isLt2M) {
//         message.error('Image must smaller than 2MB!');
//     }
//     return isJpgOrPng && isLt2M;
// };
const Student = () => {
    // 渲染页面全部数据
    const getall = () => {
        scree().then(res => {
            // console.log(res);

            // console.log(res.data, "res");
            const list = res.data.map(item => ({ ...item, key: item.SceneId }))
            // console.log(list, 'list');
            SetDataList(list)
        })

    };
    // 自动调用渲染页面数据请求
    useEffect(() => {
        getall()
    }, [])
    // 搜索栏
    const AdvancedSearchForm = () => {
        const { token } = theme.useToken();
        const [form] = Form.useForm();
        const [expand, setExpand] = useState(false);
        const formStyle = {
            maxWidth: 'none',
            background: token.colorFillAlter,
            borderRadius: token.borderRadiusLG,
            padding: 10,
        };
        const onChange = (value, dateString) => {
            // console.log('Selected Time: ', value);
            // console.log('Formatted Selected Time: ', dateString);
        };
        const onOk = (value) => {
            // console.log('onOk: ', value);
        };

        // 添加


        return (
            <Form form={form} name="advanced_search" style={formStyle} onFinish={onFinish}
                initialValues={{ id: undefined, xinming: undefined, id2: 0 }}
            >
                <Row gutter={24}>
                    <Col span={8}>
                        <Form.Item
                            name='id'
                            label='关键词'
                            rules={[
                                {

                                    message: 'Input something!',
                                },
                            ]}


                        >
                            <Input placeholder="标题关键词" />
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item
                            name='zhuangtai'//初始化动态变得数据
                            label='状态'
                        >
                            {/* <Input placeholder="placeholder" /> */}
                            <Select >
                                <Option value={undefined}>全部</Option>
                                <Option value={0}>上架</Option>
                                <Option value={1}>下架</Option>
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item
                            name='time'//初始化动态变得数据
                            label='创建时间'>

                            <Space>
                                <DatePicker showTime onChange={onChange} onOk={onOk} placeholder="请选择时间" />

                            </Space>
                        </Form.Item>
                    </Col>
                </Row>
                {/* 按钮 */}
                <Row>
                    <Col
                        span={24}
                        style={{
                            textAlign: 'center',

                        }}
                    >

                        <Button type="primary" htmlType="submit"
                        >
                            筛选
                        </Button>
                        <Button
                            style={{
                                margin: '0 .8rem',
                            }}
                            onClick={() => {
                                getall()
                            }}
                        >
                            重置
                        </Button>
                    </Col>
                </Row>
            </Form>
        );
    };
    // 点击筛选后的数据及请求  查询
    const onFinish = (values) => {
        console.log(values);
        getcx(values).then(res => {

            if (res.code == 200) {

                const list = res.data.map(item => ({ ...item, key: item.SceneId }))
                SetDataList(list);
                message.success("查询成功")
            } else {
                message.success("查询失败")

            }
        })

    };
    // 编辑日期
    const dateFormat = 'YYYY-MM-DD';
    // 删除
    const delcc = (dd) => {
        // console.log(dd);
        delcj(dd).then(res => {
            
            if (dd.SceneShelf == true) {
                message.success("不可删除")
            } else {
                if (res.code == 200) {
                    console.log(res);
                    getall()
                    message.success('删除成功')
                } else {
                    message.success('服务器出错')
                }
            }


        })
    };
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isModalOpen1, setIsModalOpen1] = useState(false);

    // 添加
    const add = () => {
        setIsModalOpen(true);
    };
    const onFinishok = (values) => {
        console.log('onFinishok', values);
        const myFormData = new FormData()
        myFormData.append('file', values.SceneImg.file.originFileObj)
        fetch('/api/upload', {
            method: 'POST',
            body: myFormData
        })
            .then(res => {
                console.log(res.status); // 打印 HTTP 响应状态码
                return res.text(); // 将响应转换为文本
            })
            .then(text => {
                const imageUrl = text.trim()
                values.SceneImg = imageUrl;

                addsc(values).then(res => {
                    if (res.code === 200) {
                        //获取成功
                        // res.data
                        message.success('添加成功');
                        getall()
                    }
                }).catch(err => {
                    message.error('获取所有商品数据失败');
                })
            })
        // .catch(error => console.error(error));
        console.log('Received values of form: ', values);
    }
    const onFinishFailedok = (values) => {
        // console.log('onFinishFailed:', values);

    }
    const [selectionType, setSelectionType] = useState('checkbox');
    const [dataList, SetDataList] = useState([]);
    //编辑的ID
    const [dataID, setDateID] = useState([])
    // 编辑
    const [list, setlist] = useState([]);
    const bianji = (row) => {
        setDateID(row.SceneId)
        // console.log(row);
        const dateStr = row.SceneTime;
        const date = new Date(dateStr);
        date.setDate(date.getDate() + 1);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate() - 1).padStart(2, '0');
        const formattedDate = `${year}-${month}-${day}`; // "2023-04-10"
        row.SceneTime = formattedDate

        setlist(row)
        setIsModalOpen1(true);
    };
    const onFinishok1 = (values) => {
        let list = []
        list.push(values)
        let op = list.map((item) => ({ ...item, dataID: dataID }))
        editsc(op[0]).then(res => {
            if (res.code == 200) {
                message.success("修改成功")
                getall();
            } else {
                message.success("修改失败")
            }
        })
    }
    const onFinishFailedok1 = (values) => {
        // console.log('onFinishFailed:', values);

    }

    // 表格样式
    const columns = [
        {
            title: '序号',
            dataIndex: 'SceneId',
            key: 'id'
        },
        {
            title: '名称',
            dataIndex: 'SceneNanme',
            key: 'name'
        },
        {
            title: '封面图',
            key: 'img',
            render: (_, record) => (
                <Space size="middle">
                    <img src={'/api' + record.SceneImg} alt="" />
                </Space>
            ),
        },
        {
            title: '是否状态',

            key: 'zhuangt',
            render: (text, record, index) => {
                return (
                    <Switch
                        defaultChecked={record.SceneShelf}
                        disabled

                    />
                );
            },

        },
        {
            title: '商品数',
            dataIndex: 'SceneSl',
            key: 'shul'
        },
        {
            title: '添加时间',
            dataIndex: 'SceneTime',
            key: 'time',
            render: (text, record) => {
                // console.log(record);
                const dateStr = record.SceneTime;
                const date = new Date(dateStr);
                date.setDate(date.getDate() + 1);
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate() - 1).padStart(2, '0');
                const formattedDate = `${year}-${month}-${day}`; // "2023-04-10"
                // console.log(formattedDate);
                return (
                    <span>{formattedDate}</span>
                )
            }
        },
        {
            title: '操作',
            render: (_, record) => (
                <Space size="small">
                    {/* <a type={"default"} onClick={() => {
                    edit(record)
                }}>编辑</a> */}
                    <a type={"default"} onClick={() => {
                        bianji(record)
                    }}>编辑</a>
                    <Link to="/index/Merchandise">商品管理</Link>
                    <a type={"spgl"} onClick={() => { delcc(record) }}>删除</a>

                </Space>
            ),
        },
    ];

    // rowSelection object indicates the need for row selection
    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
            console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        },
        getCheckboxProps: (record) => ({
            disabled: record.name === 'Disabled User',
            // Column configuration not to be checked
            name: record.name,
        }),
    };
    // 图片头像函数
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState();
    const handleChange = (info) => {
        console.log(info, '图片');
        // if (info.file.status === 'uploading') {
        //     setLoading(true);
        //     return;
        // }
        // if (info.file.status === 'done') {
        //     // Get this url from response in real world.
        //     getBase64(info.file.originFileObj, (url) => {
        //         setLoading(false);
        //         setImageUrl(url);
        //     });
        // }
        const isJpgOrPng = info.file.type === 'image/jpeg' || info.file.type === 'image/png' || info.file.type === 'image/jpg';
        if (!isJpgOrPng) {
            return message.error('图片后缀格式不对');
        }
        const isLt2M = info.file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            return message.error('最大只能上传2m的图片');
        }
        // 将文件对象转换格式
        getBase64(info.file.originFileObj, (url) => {
            setImageUrl(url);
        })
    };
    const customRequest = () => {
        console.log('zhixingle');
    }
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div
                style={{
                    marginTop: 8,
                }}
            >
                Upload
            </div>
        </div>
    );
    //改变编辑中 上下架的状态
    const onSwitchChange = (checkedValue) => {
        setlist((prevState) => ({
            ...prevState,
            SceneShelf: checkedValue
        }));
    };
    return (
        <div className='all'>
            <div className='shaix'>
                <h1>筛选查询</h1>
                <p>收起＞</p>
            </div>
            <div className='ssk'>
                <AdvancedSearchForm />

            </div>
            <div className='table'>
                {/* <Radio.Group
                    onChange={({ target: { value } }) => {
                        setSelectionType(value);
                    }}
                    value={selectionType}
                >

                </Radio.Group> */}

                <Divider />
                <div className='tianjia'>
                    <p className="heder-text">
                        数据列表
                    </p >
                    <div className='hederText'>
                        <p type={"default"} onClick={add}

                        >添加</p>
                    </div>

                </div>
                {/* <div onClick={aaa}>获取res</div> */}
                <Table pagination={{ pageSize: 5 }}
                    rowSelection={{
                        type: selectionType,
                        ...rowSelection,
                    }}
                    columns={columns}
                    dataSource={dataList}
                />
                {/* <Pagination
                    total={30}
                    showSizeChanger
                    showQuickJumper
                    showTotal={(total) => `Total ${total} items`}
                /> */}
            </div>
            <>
                <Modal title="添加场景专区" open={isModalOpen} footer={null}>
                    <Form
                        name="basic"
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 16 }}
                        style={{ maxWidth: 600 }}
                        onFinish={onFinishok}
                        onFinishFailed={onFinishFailedok}
                        autoComplete="off"
                    >
                        <Form.Item
                            label="场景名称"
                            name="SceneNanme"
                            rules={[{ required: true, message: '场景名称' }]}
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item
                            label="封面图"
                            name="SceneImg"
                            rules={[{ required: true, message: '封面图' }]}
                        >
                            <Upload
                                name="avatar"
                                listType="picture-card"
                                className="avatar-uploader"
                                showUploadList={false}
                                action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                                // beforeUpload={beforeUpload}
                                onChange={handleChange}
                                customRequest={customRequest}
                            >
                                {imageUrl ? (
                                    <img
                                        src={imageUrl}
                                        alt="avatar"
                                        style={{
                                            width: '100%',
                                        }}
                                    />
                                ) : (uploadButton)}
                            </Upload>
                        </Form.Item>

                        <Form.Item
                            label="上架状态"
                            name="SceneShelf"
                            rules={[{ required: true, message: '状态必选' }]}
                        >
                            <Select>
                                <Option value={0}>上架</Option>
                                <Option value={1}>下架</Option>
                            </Select>
                        </Form.Item>

                        <Form.Item
                            label="商品数量"
                            name="SceneSl"
                            rules={[{ required: true, message: '数量必填' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="上架时间"
                            name="SceneTime"
                            rules={[{ required: true, message: '上架时间必选' }]}
                        >
                            <DatePicker />

                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit" className='btnoo' onClick={() => {
                                setIsModalOpen(false);
                            }}>
                                确定
                            </Button>
                            <Button type="primary" className='btnoo' onClick={() => {
                                setIsModalOpen(false);
                            }}>
                                取消
                            </Button>
                        </Form.Item>
                    </Form>

                </Modal>
            </>
            <>
                <Modal title="编辑场景专区" open={isModalOpen1} footer={null} destroyOnClose={true}>
                    <Form
                        name="basic"
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 16 }}
                        style={{ maxWidth: 600 }}
                        onFinish={onFinishok1}
                        onFinishFailed={onFinishFailedok1}
                        autoComplete="off"
                        initialValues={{ SceneNanme: list.SceneNanme, SceneImg: list.SceneImg, SceneShelf: list.SceneShelf, SceneSl: list.SceneSl }}
                    >
                        <Form.Item
                            label="场景名称"
                            name="SceneNanme"
                            rules={[{ required: true, message: '场景名称' }]}
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item
                            label="封面图"
                            name="SceneImg"
                            rules={[{ required: true, message: '封面图' }]}
                        >
                            <Upload
                                name="avatar"
                                listType="picture-card"
                                className="avatar-uploader"
                                showUploadList={false}
                                action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                                // beforeUpload={beforeUpload}
                                onChange={handleChange}
                                customRequest={customRequest}
                            >
                                {imageUrl ? (
                                    <img
                                        src={imageUrl}
                                        alt="avatar"
                                        style={{
                                            width: '100%',
                                        }}
                                    />
                                ) : (uploadButton)}
                            </Upload>
                        </Form.Item>

                        <Form.Item
                            label="上架状态"
                            name="SceneShelf"
                            rules={[{ required: true, message: '状态必选' }]}
                        >
                            <Switch checked={list.SceneShelf} onChange={(checkedValue) => onSwitchChange(checkedValue)} />
                        </Form.Item>

                        <Form.Item
                            label="商品数量"
                            name="SceneSl"
                            rules={[{ required: true, message: '数量必填' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="上架时间"
                            name="SceneTime"
                            rules={[{ required: true, message: '上架时间必选' }]}
                        >
                            <DatePicker defaultValue={dayjs(list.SceneTime, dateFormat)} format={dateFormat} />

                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit" className='btnoo' onClick={() => {
                                setIsModalOpen1(false);
                            }}>
                                确定
                            </Button>
                            <Button type="primary" className='btnoo' onClick={() => {
                                setIsModalOpen1(false);
                            }}>
                                取消
                            </Button>
                        </Form.Item>
                    </Form>

                </Modal>
            </>
        </div>
    );
}

export default Student;